﻿namespace Pap.Web.Modules.Membership.ViewModel
{
    using System;
    using System.Collections.Generic;
    using System.Linq.Expressions;
    using Microsoft.Practices.ServiceLocation;
    using Pap.Data;
    using Pap.Data.Abstraction.Utils;
    using Pap.Web.Utils;

    /// <summary>
    /// Users List ViewModel class
    /// </summary>
    public class UsersListViewModel : IViewModel
    {
        /// <summary>
        /// private membership repository object
        /// </summary>
        private IMembershipRepository _MembershipRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="UsersListViewModel"/> class.
        /// </summary>
        /// <param name="membershipRepository">The membership repository.</param>
        public UsersListViewModel(IMembershipRepository membershipRepository)
        {
            this._MembershipRepository = membershipRepository;
        }

        /// <summary>
        /// Finds Users with the specified partial name.
        /// </summary>
        /// <param name="partialName">The partial name.</param>
        /// <returns>
        /// the collection of users
        /// </returns>
        public IEnumerable<IUser> Find(string partialName)
        {
            Expression<Func<IUser, bool>> whereFunc =
                user => (user.Username.Contains(partialName) || user.DisplayName.Contains(partialName));

            return this._MembershipRepository.FindUsers(whereFunc);
        }

        /// <summary>
        /// Delete all users with IDs specified.
        /// </summary>
        /// <param name="usersIds">The users ids.</param>
        public void DeleteAll(List<Guid> usersIds)
        {
            using (IUnitOfWork transaction = ServiceLocator.Current.GetInstance<IUnitOfWork>())
            {
                _MembershipRepository.DeleteUsers(u => usersIds.Contains(u.UserID));
                transaction.Commit();
            }
        }

        /// <summary>
        /// Selects all users.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<IUser> SelectAllUsers()
        {
            return this._MembershipRepository.FindUsers(r => true);
        }
    }
}
